package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_lifestyle.bp_fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.View
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.bp.hearthealth.pulse.lnapps.R
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseFragment
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.databinding.LifeStyleWebViewLayoutBgBinding


class BpLifeStyleWebViewFragment : BpBaseFragment<LifeStyleWebViewLayoutBgBinding>() {

    override fun loadDataOnce() {
        super.loadDataOnce()
        initView()
    }

    private fun initView() {
        binding.apply {
            swiperefresh.setOnRefreshListener {
                Handler(Looper.myLooper()!!).postDelayed(
                    { swiperefresh.isRefreshing = false }, 2000
                )
                laodWebView()
            }
            laodWebView()
        }
    }

    @SuppressLint("SetJavaScriptEnabled", "ClickableViewAccessibility")
    private fun laodWebView() {
        binding.wvBrowserView.settings.run {
            setSupportZoom(true)
            javaScriptEnabled = true
            domStorageEnabled = true
//            builtInZoomControls = true//支持缩放
            loadWithOverviewMode = true//内容过宽也会适应屏幕宽度
            useWideViewPort = true//WebView支持双击缩放
            loadsImagesAutomatically = true
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
        }
        binding.apply {
            wvBrowserView.loadUrl(Constants.NEWS_URL)
            // WebView 加载网页时，加载进度会发生变化
            wvBrowserView.webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView, progress: Int) {
                    if (progress == 100) {
                        //加载完成
                        LogUtil.i("onProgressChanged 加载完成")
                    }
                }
            }
            wvBrowserView.webViewClient = object : WebViewClient() {
                //WebView 完全加载一个网页时
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    //H5页面展示
                    AppsFlyerUtils.trackEvent("lifestyle_H5_show")
                    LogUtil.i("onPageFinished 加载完成")
                }

                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                }

                override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler,
                    error: SslError?
                ) {
                    val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
                    builder.setMessage(R.string._error_ssl_cert_invalid_str)
                    builder.setPositiveButton(R.string._continue_str
                    ) { dialog, which -> handler.proceed() }
                    builder.setNegativeButton(R.string._cancel_str
                    ) { dialog, which -> handler.cancel() }
                    val dialog: AlertDialog = builder.create()
                    dialog.show()
                }
            }
            //处理WebView返回事件
            wvBrowserView.setOnKeyListener(object : View.OnKeyListener {
                override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
                    if (keyCode == KeyEvent.KEYCODE_BACK && wvBrowserView.canGoBack()) {
                        if (event?.action == KeyEvent.ACTION_DOWN) {
                            wvBrowserView.goBack()
                            return true
                        }
                        return true
                    }
                    return false
                }
            })
            (this@BpLifeStyleWebViewFragment.parentFragment as BpLifeStyleFragment?)?.setPagingEnabled(
                false
            )
        }
    }
}